/*
 * @Description: 路由
 * @Date: 2021-09-11 22:26:52
 * @LastEditTime: 2021-12-07 23:40:49
 * @FilePath: \vue-test\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/user'
import prod from './prod'
const Layout = () => import(/* webpackChunkName: "Home" */ '@/components/Layout')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    children: [
      ...prod
    ]
  }
]

const router = new VueRouter({
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('savedPosition', savedPosition)
          resolve(savedPosition)
        }, 500)
      })
    } else {
      return { x: 0, y: 0 }
    }
    // return 期望滚动到哪个的位置 -让页面滚动到顶部  return { x: 0, y: 0 }
  },
  routes
})

// 判断是否登录
router.beforeEach((to, from, next) => {
  const token = getToken()
  const requireAuth = to.matched.some(res => res.meta.requireAuth)
  if (requireAuth) {
    // 判断缓存里面是否有token ，在登录时已经保存在cookie里。
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
})

export default router
